#!/usr/bin/env python3
"""
批量修复DataPlexus系统中剩余的时区问题
自动替换所有datetime.utcnow为get_shanghai_now
"""

import os
import re
from pathlib import Path

def fix_file_timezone(file_path):
    """修复单个文件的时区问题"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # 检查是否需要添加时区工具导入
        needs_timezone_import = 'datetime.utcnow' in content or 'get_shanghai_now' in content
        has_timezone_import = 'from app.utils.timezone_utils import get_shanghai_now' in content
        
        if needs_timezone_import and not has_timezone_import:
            # 查找合适的位置添加导入
            lines = content.split('\n')
            import_line_index = -1
            
            # 寻找最后一个from app.xxx import语句的位置
            for i, line in enumerate(lines):
                if line.strip().startswith('from app.') and 'import' in line:
                    import_line_index = i
            
            if import_line_index >= 0:
                lines.insert(import_line_index + 1, 'from app.utils.timezone_utils import get_shanghai_now')
                content = '\n'.join(lines)
        
        # 替换所有datetime.utcnow()为get_shanghai_now()
        content = re.sub(r'datetime\.utcnow\(\)', 'get_shanghai_now()', content)
        
        # 如果内容有变化，写回文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            return True
        
        return False
        
    except Exception as e:
        print(f"处理文件失败: {file_path} - {e}")
        return False

def main():
    print("🔧 批量修复DataPlexus时区问题")
    print("=" * 50)
    
    backend_dir = Path(__file__).parent.parent / 'backend'
    
    # 需要修复的文件列表（根据验证脚本的结果）
    files_to_fix = [
        'app/core/init_auth_db.py',
        'app/services/lineage_storage_service.py',
        'app/services/lineage_sync_service.py',
        'app/services/route_service.py',
        'app/services/sync_service.py',
        'scripts/init_routes.py'
    ]
    
    fixed_count = 0
    
    for file_path in files_to_fix:
        full_path = backend_dir / file_path
        if full_path.exists():
            print(f"📝 处理文件: {file_path}")
            if fix_file_timezone(full_path):
                print(f"   ✅ 修复完成")
                fixed_count += 1
            else:
                print(f"   ⏭️  无需修复")
        else:
            print(f"   ❌ 文件不存在: {file_path}")
    
    print()
    print(f"🎉 批量修复完成！")
    print(f"   - 处理文件数: {len(files_to_fix)}")
    print(f"   - 修复文件数: {fixed_count}")
    
    return fixed_count > 0

if __name__ == "__main__":
    success = main()
    exit(0 if success else 1)
